/**
 * 网络状态检测工具
 */

export class NetworkStatus {
    constructor() {
        this.online = navigator.onLine;
        this.listeners = new Set();

        window.addEventListener('online', this.handleOnline);
        window.addEventListener('offline', this.handleOffline);
    }

    handleOnline = () => {
        this.online = true;
        this.notifyListeners();
    };

    handleOffline = () => {
        this.online = false;
        this.notifyListeners();
    };

    notifyListeners = () => {
        this.listeners.forEach((listener) => listener(this.online));
    };

    addListener = (listener) => {
        this.listeners.add(listener);
        return () => this.listeners.delete(listener);
    };

    isOnline = () => {
        return this.online;
    };

    destroy() {
        window.removeEventListener('online', this.handleOnline);
        window.removeEventListener('offline', this.handleOffline);
        this.listeners.clear();
    }
}

// 单例模式导出
export const networkStatus = new NetworkStatus();
